// ==UserScript==
// @name         智联招聘信息提取
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       zhangsan
// @match        https://*.zhaopin.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=zhaopin.com
// @grant        GM_xmlhttpRequest
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js
// ==/UserScript==

(function() {
    'use strict';

// 基本配置
let default_port = 5000;

//添加控件
var container = document.createElement('div');
container.style.position = 'fixed';
container.style.top = '80px';
container.style.right = '20px';
container.style.backgroundColor = 'transparent';
container.style.color = 'black';
container.style.padding = '5px ff0000';
container.style.border = '1px white';
// container.style.border-bottom-left-radius = '4px';
// container.style.border-bottom-right-radius = '4px';
// container.style.border-top-left-radius = '4px';
// container.style.border-top-right-radius = '4px';
container.style.zIndex = '9999';

var textNode = document.createTextNode('端口:');
var inputBox = document.createElement('input');
inputBox.type = 'text';
inputBox.value = `${default_port}`;
inputBox.style.width = '60px';
inputBox.style.height = '20px';
inputBox.style.padding = '5px';
inputBox.style.border = '1px solid black';

var button = document.createElement('button');
button.innerHTML = '开始扫描';
button.style.padding = '5px';
button.style.backgroundColor = 'transparent';
button.style.color = 'black';
button.style.border = '1px white';

container.appendChild(textNode);
container.appendChild(inputBox);
container.appendChild(button);
document.body.appendChild(container);

// 为按钮添加悬停事件监听器
button.addEventListener("mouseover", () => {
  // 更改鼠标指针的样式
  button.style.cursor = "pointer";
});

class JobServer {
    // constructor
    constructor(arg, arg1) {
        this.port = arg;
        this.url = "";
        this.respDoneCallback = arg1;

        this.scanState = 0;
        this.waitServerResp = 0;
        this.currentPageUrl = "";
        this.isEndPage = 0;
    }
     // Getter
     getServerUrl(){
         this.url = `http://127.0.0.1:${this.port}/`;
         return this.url;
     }

    toggleCtrl(port){
        if (this.scanState == 0){
            this.scanState = 1;
            this.currentPageUrl = "";

            this.setServerPort(port);
            this.url = `http://127.0.0.1:${this.port}/`;
        }else {
            this.scanState = 0;
            this.currentPageUrl = "";
        }

        return this.scanState;
    }
    // Method
    setServerPort(port) {
        var temp = parseInt(port);
        // console.log("11", temp);
        if (!isNaN(temp))
        {
            this.port = temp;
        }
    }

    WaitServerRespCallback(){
        if (this.scanState){
            this.scanState = 3;
        }
    }

    postJobInfo() {
        // 获取当前页面的HTML代码
        var html = document.documentElement.outerHTML;
        var url = document.URL
        // console.log(url, html);

        // 发送POST请求到Python服务器
        GM_xmlhttpRequest({
            method: 'POST',
            url: this.url + 'parse',
            data: JSON.stringify({ url: url, html: html }),
            headers: {
                'Content-Type': 'application/json'
            },
            onload: this.respDoneCallback
        });
    }

    switchNextPage(){
        // 获取页数
        var page = document.evaluate("//ul[@class='el-pager']//li", document, null, XPathResult.ANY_TYPE, null);
        // console.log("输出元素信息(page):", typeof(page), page.resultType, page);
        let cur_page;
        var currentPage = 1;
        var maxPage = 1;
        while (cur_page = page.iterateNext()) {
            // console.log("输出页面信息(cur_page):", cur_page.nodeName, cur_page.attributes, cur_page.nodeType, cur_page.value, cur_page);
            var temp = parseInt(cur_page.textContent);

            // console.log(`[11]${temp}`);
            if ($(cur_page).hasClass('active')) {
                currentPage = parseInt(cur_page.textContent);
                // console.log(`[12]当前页Id:${currentPage}`);
            }

            // console.log("21", temp);
            if (!isNaN(temp) && (maxPage < temp))
            {
                // console.log(`[22]${maxPage}=>${temp}`);
                maxPage = temp;
            }
        }

        var btn = document.evaluate("//button[@class='btn-next']", document, null, XPathResult.ANY_TYPE, null);
        // console.log("输出元素信息(btn):", typeof(btn), btn.resultType, btn);
        let node;
        var result = 0;
        while (node = btn.iterateNext()) {
            // console.log("输出元素信息(node):", node.nodeName, node.attributes, node.nodeType, node.value, node);

            if($(node).prop("disabled") == true){
                console.log(`[${maxPage}]已跳转至末尾页`)
            } else {
                console.log(`[${currentPage}/${maxPage}]即将跳转至下一页`)
                node.click();
                result = 1;
            }

            break;
        }

        return result;
    }

    autoScanProcess(){
        if (this.scanState){
            let nowUrl = window.location.href;
            // 当计时器为零时执行操作
            if (this.currentPageUrl != nowUrl) {
                this.currentPageUrl = nowUrl;
                this.scanState = 2;
                // console.log("开始爬取岗位信息")
                this.postJobInfo();
                // console.log("autoScanProcess, page change", nowUrl, this.scanState, this.waitServerResp);
            }else if (this.scanState == 1) {
                this.currentPageUrl = nowUrl;
                this.scanState = 2;
                // console.log("开始爬取岗位信息")
                this.postJobInfo();
                // console.log("autoScanProcess, page change", nowUrl, this.scanState, this.waitServerResp);
            }else if (this.scanState == 3) {
                if (this.switchNextPage()) {
                    this.scanState = 1;
                } else {
                    // this.scanState = 4;
                    this.scanState = 1;
                }
            }
        }
    }
}

// 初始化job句柄
var job_server = 0;
function postDoneCallback(response){
    job_server.WaitServerRespCallback();
    console.log("Host Response:", response.responseText, job_server.scanState);
}

job_server = new JobServer(default_port, postDoneCallback);
console.log("Start BossZhiPin Scan", job_server.getServerUrl());

// 按钮事件处理
function work_scan_process() {
    // 获取需要修改的控件
    var element = button;
    var state = job_server.toggleCtrl(inputBox.value);

    if (state){
        element.innerHTML = '停止扫描';
        console.log("开始扫描", job_server.getServerUrl());
    }else {
        element.innerHTML = '开始扫描';
        console.log("停止扫描");
    }
}
button.addEventListener('click', work_scan_process);

// 每隔一秒执行一次倒计时
function timer_callback() {
    job_server.autoScanProcess();
}
setInterval(timer_callback, 2000);

})();